const app=getApp();
const db=wx.cloud.database();
const _=db.command;
const $ = db.command.aggregate
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // onPullDownRefresh: function () {
    //   wx.stopPullDownRefresh()
    // },
    myinfo: null

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let openid = app.globalData.openid;
    if(!openid){
      wx.cloud.callFunction({
        name:'getOpenId'
      }).then(res=>{
        openid=res.result._openid
        console.log(openid)
        this.getInfo(openid)
        app.globalData.openid=openid
      })
    }
    else{
      this.getInfo(openid);
    }
  },

  onShow(){

  },

  getInfo(openid){
    db.collection('user').aggregate().match({
      _openid:openid,
      history:_.exists(true)
    }).project({
      jonnerName:1,
      jf:1,
      image:'$userWxInfo.avatarUrl',
      gender:'$userWxInfo.gender',
      city:'$userWxInfo.city',
      gametimes:$.size('$history'),
      avg:$.divide([$.sum('$history'), $.size('$history')]),
      firstcount:$.size($.filter({
        input: '$history',
        as: 'item',
        cond: $.eq(['$$item', 1])
      })),
      secondcount:$.size($.filter({
        input: '$history',
        as: 'item',
        cond: $.eq(['$$item', 2])
      })),
      thirdcount:$.size($.filter({
        input: '$history',
        as: 'item',
        cond: $.eq(['$$item', 3])
      })),
      lastcount:$.size($.filter({
        input: '$history',
        as: 'item',
        cond: $.eq(['$$item', 8])
      }))
    }).end().then(res=>{
      if(res.list.length==1){
        this.setData({
          myinfo:res.list[0]
        })
      }
      else{
        wx.showToast({
          title: '你还没参加过任何对局',
          icon:'none'
        })
        db.collection('user').aggregate().match({
          _openid:openid
        }).project({
          jonnerName:1,
          jf:1,
          image:'$userWxInfo.avatarUrl',
          gender:'$userWxInfo.gender',
          city:'$userWxInfo.city',
        }).end().then(res=>{
          this.setData({
            myinfo:res.list[0]
          })
        })
      }
    })
  },

  tozw(){
    let openid = app.globalData.openid;
    this.getInfo(openid)
  }
})
